import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

X = np.array([
    [1, 2],  # 正例点 x1
    [2, 3],  # 正例点 x2
    [3, 3],  # 正例点 x3
    [2, 1],  # 负例点 x4
    [3, 2]   # 负例点 x5
])
y = np.array([1, 1, 1, 0, 0])

# 创建SVC模型获取w，b和支持向量
model = svm.SVC(kernel='linear', C=1E10)
model.fit(X, y)
w = model.coef_[0]
b = model.intercept_[0]
support_vectors = model.support_vectors_
print(f"w: {w}")
print(f"b: {b}")
print(f"支持向量: {support_vectors}")

# 绘制图形
plt.figure(figsize=(8, 6))
# 绘制正例点（黑色）和负例点（红色）
plt.scatter(X[y == 1, 0], X[y == 1, 1], c='black', marker='o', s=100, label='正例点')
plt.scatter(X[y == 0, 0], X[y == 0, 1], c='red', marker='o', s=100, label='负例点')

# 绘制分离超平面
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()

# 创建网格
xx = np.linspace(0, 4, 40)
yy = np.linspace(0, 4, 40)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = model.decision_function(xy).reshape(XX.shape)

# 绘制决策边界和间隔边界
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
           linestyles=['--', '-', '--'])

# 标记支持向量
ax.scatter(support_vectors[:, 0], support_vectors[:, 1], s=100,
           linewidth=1, facecolors='none', edgecolors='k')
plt.xlabel('x^(1)')
plt.ylabel('x^(2)')
plt.title('Problem 7.2 SVM_result')
plt.savefig('svm_result.png')